package com.medical.literature.user.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * JWT认证过滤器
 * 从请求头中获取用户信息并设置到Spring Security上下文中
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 从请求头中获取用户ID和用户名
        String userIdStr = request.getHeader("X-User-Id");
        String username = request.getHeader("X-Username");
        
        log.info("JwtAuthenticationFilter - X-User-Id: {}, X-Username: {}", userIdStr, username);
        
        // 如果请求头中包含用户信息，则设置认证信息
        if (userIdStr != null && username != null) {
            try {
                Long userId = Long.parseLong(userIdStr);
                
                // 创建认证对象
                UsernamePasswordAuthenticationToken authentication = 
                    new UsernamePasswordAuthenticationToken(
                        userId, // 使用用户ID作为principal
                        null, 
                        Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
                    );
                
                // 将认证信息设置到安全上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
                
                log.info("成功设置用户认证信息，用户ID: {}, 用户名: {}", userId, username);
            } catch (NumberFormatException e) {
                log.warn("无效的用户ID格式: {}", userIdStr);
            }
        }
        
        filterChain.doFilter(request, response);
    }
}